package tw.com.hitevision.whiteboard.android.widgets.MeasurementTools;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;

import tw.com.hitevision.whiteboard.android.R;

public class MeasurementToolLayer extends ConstraintLayout {

    public MeasurementToolLayer(Context context) {
        super(context);
        init(context);
    }

    public MeasurementToolLayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MeasurementToolLayer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        inflate(context, R.layout.measurement_tool_layer_layout, this);
    }

    public void addRuler(View ruler) {
        if (ruler == null) {
            return;
        }
        removeRuler(ruler);

        ConstraintLayout layout = findViewById(R.id.measurement_tool_layer_root);
        int id = View.generateViewId();
        ruler.setId(id);
        layout.addView(ruler);

        ConstraintSet set = new ConstraintSet();
        set.clone(layout);
        int parentId = getId();
        set.constrainWidth(id, ConstraintSet.MATCH_CONSTRAINT);
        set.constrainHeight(id, ConstraintSet.MATCH_CONSTRAINT);
        set.connect(id, ConstraintSet.START, parentId, ConstraintSet.START);
        set.connect(id, ConstraintSet.TOP, parentId, ConstraintSet.TOP);
        set.connect(id, ConstraintSet.RIGHT, parentId, ConstraintSet.RIGHT);
        set.connect(id, ConstraintSet.BOTTOM, parentId, ConstraintSet.BOTTOM);
        set.applyTo(this);
    }

    public void removeRuler(View view) {
        if (view == null) {
            return;
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
    }
}
